package android.cmpe451.group7.dbrequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.cmpe451.group7.util.GlobalVariables;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

/**
 * Task to retrieve a JSON object from the Internet
 * 
 * Only pre/post execute methods have to be written to use this object when GUI
 * changes are needed
 * 
 * @param <T>
 *            Class of the mapped JSON object
 */
public abstract class RetrieveJSONTask<T> extends
		AsyncTask<String, Void, WebServiceResponse<T>> {

	// Java class that the JSON object is converted to
	protected WebServiceResponse<T> gsonObject;

	// Activity that calls this async task
	protected Activity activity;

	public RetrieveJSONTask(Activity activity) {
		this.activity = activity;
	}

	// this is for using the class when updating gui is not needed
	public RetrieveJSONTask() {
		this(null);
	}

	@SuppressWarnings("unchecked")
	protected WebServiceResponse<T> doInBackground(Type type, String... args) {
		InputStream source = retrieveStream(args[0]);
		if (source == null) {
			return null;
		}
		Gson gson = new Gson();
		String resultJson = getStringFromInputStream(source);
		Log.w("RESULT-JSON", resultJson);
		gsonObject = (WebServiceResponse<T>) gson.fromJson(resultJson, type);
		return gsonObject;
	}

	/**
	 * Method to turn the response into a input stream
	 * 
	 * @param url
	 *            name of the webpage to read
	 * @return stream that contains the page
	 */
	public static InputStream retrieveStream(String url) {
		DefaultHttpClient client = new DefaultHttpClient(
				GlobalVariables.httpParameters);
		HttpGet getRequest = new HttpGet(url);
		try {
			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}

			HttpEntity getResponseEntity = getResponse.getEntity();
			return getResponseEntity.getContent();
		} catch (IOException e) {
			getRequest.abort();
		}
		return null;
	}

	/**
	 * Reads an input stream into a string
	 * 
	 * @param is
	 * @return
	 */
	public static String getStringFromInputStream(InputStream is) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
}
